<template>
  <div class="page-container">
    <el-container>
      <el-aside width="280px" class="page-aside" v-drag v-collapse>
        <div class="tree-box">
          <el-row style="padding-right: 20px;">
            <el-input
              placeholder="流程搜索"
              v-model="filterText"
              style="margin-right: 10px"
              clearable
            ></el-input>
          </el-row>
        </div>
        <el-row class="page-aside-grow">
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="treeData"
            node-key="id"
            :props="treeProps"
            :highlight-current="true"
            :default-expanded-keys="['0']"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
          ></el-tree>
        </el-row>
      </el-aside>
      <el-main style="--el-main-padding: 10px;">
        <div
          v-if="batchFormData.flowId && batchFormData.list && batchFormData.list.length === 0"
        >此流程无分支，无须配置。</div>
        <div
          v-loading="nodeLoading || editLoading"
          element-loading-text="数据加载中..."
          class="line-box"
        >
          <el-form
            :model="batchFormData"
            label-width="0px"
            ref="batchDataForm"
          >
            <div
              class="line-item"
              v-for="(line, index) in batchFormData.list"
              :key="index"
            >
              <div class="line-header">
                <div class="line-info">
                  <span v-if="line.name">线路名称：{{line.name}}</span>
                  <span>节点名称：{{line.preNodeName}}</span>
                  <span>下一节点名称：{{line.nextNodeName}}</span>
                </div>
                <div class="line-button">
                  <el-button
                    type="success"
                    @click="handleCondNewRows(line)"
                  >添加条件</el-button>
                </div>
              </div>
              <div class="line-body">
                <el-table
                  class="edit-table cond-table"
                  header-align="center"
                  ref="batchTable"
                  :data="line.condList"
                  :border="true"
                >
                  <template #empty>
                    <div class="el-table__empty-block">
                      <img src="@/assets/images/no-data.png" style="width: 100px" alt />
                      <span style="min-width: 100px">暂无数据</span>
                    </div>
                  </template>
                  <el-table-column label="条件分组" width="100" header-align="center">
                    <template #header>
                      <span style="margin-right: 5px">显示分组</span>
                      <el-tooltip content="同一分组为 and 条件，不同分组间为 or 条件">
                        <ac-icon iconId="018dca8ec9890493be26" />
                      </el-tooltip>
                    </template>
                    <template #default="scope">
                      <el-input type="number" v-model.number="scope.row.condGroup" />
                    </template>
                  </el-table-column>
                  <el-table-column label="条件来源" width="110" header-align="center" >
                    <template #header>
                      <span style="margin-right: 5px">条件来源</span>
                      <el-tooltip content="脚本：脚本中返回true/false，true：条件成立，false：不成立">
                        <ac-icon iconId="018dca8ec9890493be26" />
                      </el-tooltip>
                    </template>
                    <template #default="scope">
                      <ac-dict-select v-model="scope.row.condOrigin" dictCode="dictFlowLineCOrigin" />
                    </template>
                  </el-table-column>
                  <el-table-column label="脚本" header-align="center" >
                    <template #default="scope">
                      <ac-tree
                        v-if="scope.row.condOrigin === '2'"
                        v-model="scope.row.scriptId"
                        data-url="/system/scriptGroovy/queryTree"
                        type-select="script"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="来源节点" header-align="center" >
                    <template #default="scope">
                      <el-select
                        v-if="scope.row.condOrigin === '1'"
                        v-model="scope.row.nodeId"
                        @change="changeNode(scope.row, true)"
                        placeholder="--请选择--"
                      >
                        <el-option
                          v-for="(item, index) in nodeData"
                          :key="index"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="来源字段" header-align="center">
                    <template #default="scope">
                      <ac-remote-select
                        v-if="scope.row.condOrigin === '1' && scope.row.nodeId && scope.row.modelId"
                        v-model="scope.row.fieldName"
                        data-url="/system/dataField/queryList"
                        :query="{modelId: scope.row.modelId}"
                        idProp="fieldName"
                        nameProp="showName"
                        :loadAll="true"
                      />
                      <el-select v-else-if="scope.row.condOrigin === '1'" placeholder="--请选择--"></el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="条件类型" width="120" header-align="center">
                    <template #default="scope">
                      <ac-select
                        v-if="scope.row.condOrigin === '1'"
                        v-model="scope.row.condType"
                        options="包含,不包含,等于,不等于,大于,大于等于,小于,小于等于"
                      ></ac-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="条件值" header-align="center">
                    <template #default="scope">
                      <div style="display: flex;flex-direction: row;width: 100%" v-if="scope.row.condOrigin === '1'">
                        <div v-if="scope.row.manually !== '1'" style="flex-grow: 1">
                          <ac-remote-select
                            v-if="scope.row.fieldName"
                            v-model="scope.row.condValue"
                            data-url="/system/dataField/queryDictList"
                            :query="{modelId: nodeData.find(item => item.id === scope.row.nodeId)?.modelId, fieldName: scope.row.fieldName}"
                            idProp="key"
                            nameProp="value"
                            loadAll
                          />
                          <el-select v-else placeholder="--请选择--"></el-select>
                        </div>
                        <div v-else style="flex-grow: 1">
                          <ac-input v-model="scope.row.condValue" />
                        </div>
                        <ac-dict-switch
                          v-model="scope.row.manually"
                          dictCode="dictYesNo"
                          style="margin: 0 5px;"
                          title="手动录入"
                        />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80" header-align="center" align="center">
                    <template #default="scope">
                      <el-button
                        @click="handleCondDeleteRow(line, scope.row)"
                        type="danger"
                        link
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-form>
        </div>
        <el-row
          v-if="batchFormData.list && batchFormData.list.length > 0"
          style="margin: 10px 10px 0 0;"
        >
          <el-col :span="24" style="text-align:right">
            <el-button
              type="primary"
              :loading="editLoading"
              @click="submitBatchForm"
            >保存</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import api from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";

const filterText = ref('');
const treeData = ref([]);
const treeProps = ref({
  children: 'children',
  label: 'name',
  isLeaf: 'leaf'
});
const nodeLoading = ref(false);
const editLoading = ref(false);
const batchFormData = ref({
  list: []
});
const nodeData = ref([]);
const newCondRowFlag = ref(1);
const tree = ref();
const route = useRoute();
const batchDataForm = ref();

watch(() => filterText.value, (val) => {
  tree.value.filter(val);
});

const filterNode = (value, data, node) => {
  if (!value) return true;
  // 叶节点，根据父流程名称来判断
  if (data.leaf === true && node.parent != null && node.parent.data != null) {
    const data = node.parent.data;
    return data.name.indexOf(value) !== -1 || (data.code != null && data.code.indexOf(value) !== -1);
  }
  return data.name.indexOf(value) !== -1 || (data.code != null && data.code.indexOf(value) !== -1);
};

const nodeClick = (data, node) => {
  if (node.level > 1) {
    batchFormData.value.flowId = node.data.id;
    loadNodeDataByFlowId(batchFormData.value.flowId);
    loadNodeData(batchFormData.value.flowId);

    nextTick(() => {
      batchDataForm.value && batchDataForm.value.clearValidate();
    });
  }
};

const changeNode = (row, clean) => {
  if (clean) {
    row.modelId = '';
    row.fieldName = '';
    row.condType = '';
    row.condValue = '';
  }

  if (row.nodeId) {
    row.modelId = nodeData.value.find(item => item.id === row.nodeId)?.modelId
  }
};

const handleCondNewRows = (line) => {
  line.condList.push({
    newRowFlag: ++newCondRowFlag.value
  });
};

const handleCondDeleteRow = (line, row) => {
  for (let i=0;i<line.condList.length;i++) {
    if (row.newRowFlag !== undefined
      && row.newRowFlag === line.condList[i].newRowFlag) {
      line.condList.splice(i, 1);
      return;
    } else if (row.id !== undefined && row.id === line.condList[i].id) {
      line.condList.splice(i, 1);
      return;
    }
  }
};

// 数据批量保存
const submitBatchForm = () => {
  batchDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post('/system/flowLine/saveLineCond', batchFormData.value).then(res => {
          if(res.code === '1') {
            loadNodeData(batchFormData.value.flowId);
            ElMessage.success(res.message);
          } else {
            ElMessage.error(res.message);
          }
          editLoading.value = false
        }).catch(() => {
          editLoading.value = false
        })
      }).catch(()=>{})
    } else {
      ElMessage.error('表单数据填写不完整，请检查！');
    }
  })
};

const loadTreeData = () => {
  // 获取本页的操作按钮
  api.post(route.meta.url).then(res => {
    if(res.code === '1') {
      treeData.value = [{id: '0', name: '流程树', children: res.data}];
    } else {
      ElMessage.error(res.message);
    }
  });
};

const loadNodeData = (flowId) => {
  editLoading.value = true;
  api.post('/system/flowLine/queryBranchList', {flowId: flowId}).then(res => {
    if(res.code === '1') {
      if (res.data.length > 0) {
        batchFormData.value = Object.assign({flowId: flowId}, {list: res.data});
        batchFormData.value.list.forEach(line => {
          if (line.list) {
            line.list.forEach(cond => changeNode(cond, false))
          }
        });
      } else {
        batchFormData.value = Object.assign({flowId: flowId}, {list: []});
      }
    } else {
      ElMessage.error(res.message);
    }
    editLoading.value = false;
  }).catch(() => {
    editLoading.value = false;
  });
};

const loadNodeDataByFlowId = (flowId) => {
  nodeLoading.value = true;
  nodeData.value = [];
  api.post('/system/flowNode/queryList', {flowId: flowId, type: '10', valid: '1'}).then(res => {
    if(res.code === '1') {
      if (res.data.length > 0) {
        nodeData.value = res.data;
      } else {
        nodeData.value = [];
      }
    } else {
      ElMessage.error(res.message);
    }
    nodeLoading.value = false;
  }).catch(() => {
    nodeLoading.value = false;
  });
};

onMounted(() => {
  loadTreeData();
  batchFormData.value = Object.assign({}, {list: []});
});
</script>

<style scoped lang="scss">
.page-container {
  width: calc(100% - 10px);
  padding-right: 0!important;
}
.line-box {
  height: 1px;
  flex-grow: 1;
  overflow: auto;
  padding-right: 10px;
  min-height: 100px;
  .line-item {
    .line-header {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-bottom: 3px;
      width: 100%;
      span {
        margin-right: 30px;
      }
      .line-info {
        flex-grow: 1;
      }
      .line-button {
        flex-shrink: 0;
        width: 120px;
        text-align: right;
      }
    }
    .line-body {
      margin-bottom: 20px;
    }
  }
}
</style>